<template>
  <div class="wrap">
    <el-form
      ref="ruleFormRef"
      style="max-width: 600px"
      :model="ruleForm"
      status-icon
      :rules="rules"
      label-width="auto"
      class="ruleForm-wrap"
    >
      <el-form-item label="角色名称" prop="role_name">
        <el-input v-model="ruleForm.role_name" />
      </el-form-item>
      <el-form-item class="btn-wrap">
        <el-button type="primary" @click="submitForm(ruleFormRef)">
          创建
        </el-button>
        <el-button type="warning" plain @click="resetForm(ruleFormRef)">重置</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script setup>
import { reactive, ref } from 'vue'
import { ElMessage } from 'element-plus'
import { postData } from '@/http/request.js'
import { useRouter } from 'vue-router'
let router = useRouter()
let ruleFormRef = ref(null)

const ruleForm = reactive({
  role_name: ''
})

const rules = reactive({
  role_name: [{ required: true, message: '请输入角色名称', trigger: 'blur' }],
})

const submitForm = async (formEl) => {
  if (!formEl) return
  await formEl.validate((valid, fields) => {
    if (valid) {
      postData('/role/register', {
        role_name: ruleForm.role_name?ruleForm.role_name:'角色'
      })
        .then((res) => {
          if (res.code == 0) {
            ElMessage({
              type: 'success',
              message: '创建成功',
            })
            setTimeout(() => {
              router.push('/roleList')
            }, 3000)
          } else {
            ElMessage({
              type: 'error',
              message: '创建失败',
            })
          }
        })
        .catch((err) => {
          console.log(err)
        })
    } else {
      console.log('error submit!', fields)
    }
  })
}

const resetForm = (formEl) => {
  if (!formEl) return
  formEl.resetFields()
}
</script>
<style scope>
.wrap {
  margin: 20px 0 0 20px;
}
.btn-wrap{
  margin-top:30px;
}
</style>
